package com.sgj.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.sgj.common.constant.RedisConstant;
import com.sgj.gulimall.product.service.CategoryBrandRelationService;
import com.sgj.gulimall.product.vo.Catelog2Vo;
import com.sgj.gulimall.product.vo.Catelog2Vo.Catelog3Vo;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sgj.common.utils.PageUtils;
import com.sgj.common.utils.Query;

import com.sgj.gulimall.product.dao.CategoryDao;
import com.sgj.gulimall.product.entity.CategoryEntity;
import com.sgj.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    private CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        // 查出所有分类
        List<CategoryEntity> entityList = baseMapper.selectList(null);

        // 组装成树形结构
        // 找到所有的一级分类
        List<CategoryEntity> level1Menus = entityList.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(menu -> {
                    menu.setChildren(getChildrens(menu, entityList));
                    return menu;
                }).sorted((menu1, menu2) -> (Objects.isNull(menu1.getSort()) ? 0 : menu1.getSort()) - (Objects.isNull(menu2.getSort()) ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前菜单是否有子级菜单
        baseMapper.deleteBatchIds(asList);
    }

    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);
        Collections.reverse(parentPath);
        return parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * 级联更新所有关联的数据
     * @param category
     */
    // @Caching(evict = {
    //         @CacheEvict(value = "category", key = "'getLevel1Categorys'"),
    //         @CacheEvict(value = "category", key = "'getCatalogJson'")
    // })
    @CacheEvict(value = "category", allEntries = true)
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    // 每一个需要缓存的数据，都需要指定放在哪个名字下
    @Cacheable(value = "category", key = "#root.method.name", sync = true)
    @Override
    public List<CategoryEntity> getLevel1Categorys() {
        return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
    }

    @Cacheable(value = "category", key = "#root.methodName", sync = true)
    @Override
    public Map<String, List<Catelog2Vo>> getCatalogJson() {
        // 将数据库的多次查询变为一次
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        // 查出所有一级分类
        List<CategoryEntity> level1Categorys = getParentCid(selectList, 0L);

        // 封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream()
                .collect(Collectors.toMap(key -> key.getCatId().toString(), value -> {
                            // 查询每个一级分类下的二级分类
                            List<CategoryEntity> entityList = getParentCid(selectList, value.getCatId());
                            List<Catelog2Vo> catelog2VoList = null;
                            if (!CollectionUtils.isEmpty(entityList)) {
                                catelog2VoList = entityList.stream().map(l2 -> {
                                    Catelog2Vo catelog2Vo = Catelog2Vo.builder()
                                            .catelog1Id(value.getCatId().toString())
                                            .id(l2.getCatId().toString())
                                            .name(l2.getName())
                                            .build();
                                    // 查询当前二级分类的三级分类，封装成vo
                                    List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getCatId());
                                    if (!CollectionUtils.isEmpty(level3Catelog)) {
                                        // 封装成指定 vo 格式
                                        List<Catelog3Vo> catelog3VoList = level3Catelog.stream().map(l3 -> {
                                            Catelog3Vo catelog3Vo = Catelog3Vo.builder()
                                                    .catelog2Id(l2.getCatId().toString())
                                                    .id(l3.getCatId().toString())
                                                    .name(l3.getName())
                                                    .build();
                                            return catelog3Vo;
                                        }).collect(Collectors.toList());
                                        catelog2Vo.setCatalog3List(catelog3VoList);
                                    }
                                    return catelog2Vo;
                                }).collect(Collectors.toList());
                            }
                            return catelog2VoList;
                        }
                ));
        return parentCid;
    }

    public Map<String, List<Catelog2Vo>> getCatalogJson2() {
        // 查询缓存
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            // 若缓存中没有，则查询数据库
            Map<String, List<Catelog2Vo>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();
            return catalogJsonFromDb;
        }
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    /**
     * Redisson分布式锁
     * 随之而来的问题：缓存的数据如何和数据库保持一致性
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedissonLock() {

        // redis 分布式锁,去 redis 占位
        // 锁的名字一定不能相同，锁的粒度越小，越快
        // 锁的粒度：具体缓存的是某个数据，11号商品：product-11-lock 、 product-12-lock.....
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();

        Map<String, List<Catelog2Vo>> dataFromDb;
        try {
            // 加锁成功 执行业务
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }
        return dataFromDb;

    }

    /**
     * Redis锁从数据库查询并封装数据到redis
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithRedisLock() {

        // redis 分布式锁,去 redis 占位
        // 必须设置过期时间,防止出现加锁后服务宕机，锁无法删除，死锁的情况
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            Map<String, List<Catelog2Vo>> dataFromDb;
            try {
                // 加锁成功 执行业务
                dataFromDb = getDataFromDb();
            } finally {
                // 删除锁,由于是分布式系统，单纯对比key可能删掉其他服务的锁，必须进行值的对比  而且必须是原子操作，需要使用lua脚本
                redisTemplate.execute(new DefaultRedisScript<Long>(RedisConstant.SCRIPT, Long.class), Arrays.asList("lock"), uuid);
                // 由于以下操作不是原子性操作，所以采用lua脚本方式
                // String lock1 = redisTemplate.opsForValue().get("lock");
                // if (uuid.equals(lock1)) {
                //     redisTemplate.delete("lock");
                // }
            }
            return dataFromDb;
        } else {
            // 加锁失败 重试 等待 1 秒
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock();
        }

    }

    private Map<String, List<Catelog2Vo>> getDataFromDb() {
        // 进入锁之后，再去缓存中确定一次，如果没有才需要继续查询
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        // 若缓存不为空，直接返回
        if (StringUtils.isNotEmpty(catalogJSON)) {
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }

        // 将数据库的多次查询变为一次
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        // 查出所有一级分类
        List<CategoryEntity> level1Categorys = getParentCid(selectList, 0L);

        // 封装数据
        Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream()
                .collect(Collectors.toMap(key -> key.getCatId().toString(), value -> {
                            // 查询每个一级分类下的二级分类
                            List<CategoryEntity> entityList = getParentCid(selectList, value.getCatId());
                            List<Catelog2Vo> catelog2VoList = null;
                            if (!CollectionUtils.isEmpty(entityList)) {
                                catelog2VoList = entityList.stream().map(l2 -> {
                                    Catelog2Vo catelog2Vo = Catelog2Vo.builder()
                                            .catelog1Id(value.getCatId().toString())
                                            .id(l2.getCatId().toString())
                                            .name(l2.getName())
                                            .build();
                                    // 查询当前二级分类的三级分类，封装成vo
                                    List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getCatId());
                                    if (!CollectionUtils.isEmpty(level3Catelog)) {
                                        // 封装成指定 vo 格式
                                        List<Catelog3Vo> catelog3VoList = level3Catelog.stream().map(l3 -> {
                                            Catelog3Vo catelog3Vo = Catelog3Vo.builder()
                                                    .catelog2Id(l2.getCatId().toString())
                                                    .id(l3.getCatId().toString())
                                                    .name(l3.getName())
                                                    .build();
                                            return catelog3Vo;
                                        }).collect(Collectors.toList());
                                        catelog2Vo.setCatalog3List(catelog3VoList);
                                    }
                                    return catelog2Vo;
                                }).collect(Collectors.toList());
                            }
                            return catelog2VoList;
                        }
                ));
        // 将查出的数据放入缓存, 并设置过期时间，防止缓存雪崩
        redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(parentCid), 1, TimeUnit.DAYS);
        return parentCid;
    }

    /**
     * 本地锁从数据库查询并封装数据到redis
     * @return
     */
    public Map<String, List<Catelog2Vo>> getCatalogJsonFromDbWithLocalLock() {
        // 加锁，防止缓存击穿
        synchronized (this) {
            // 进入锁之后，再去缓存中确定一次，如果没有才需要继续查询
            String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
            // 若缓存不为空，直接返回
            if (StringUtils.isNotEmpty(catalogJSON)) {
                Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
                });
                return result;
            }

            // 将数据库的多次查询变为一次
            List<CategoryEntity> selectList = baseMapper.selectList(null);

            // 查出所有一级分类
            List<CategoryEntity> level1Categorys = getParentCid(selectList, 0L);

            // 封装数据
            Map<String, List<Catelog2Vo>> parentCid = level1Categorys.stream()
                    .collect(Collectors.toMap(key -> key.getCatId().toString(), value -> {
                                // 查询每个一级分类下的二级分类
                                List<CategoryEntity> entityList = getParentCid(selectList, value.getCatId());
                                List<Catelog2Vo> catelog2VoList = null;
                                if (!CollectionUtils.isEmpty(entityList)) {
                                    catelog2VoList = entityList.stream().map(l2 -> {
                                        Catelog2Vo catelog2Vo = Catelog2Vo.builder()
                                                .catelog1Id(value.getCatId().toString())
                                                .id(l2.getCatId().toString())
                                                .name(l2.getName())
                                                .build();
                                        // 查询当前二级分类的三级分类，封装成vo
                                        List<CategoryEntity> level3Catelog = getParentCid(selectList, l2.getCatId());
                                        if (!CollectionUtils.isEmpty(level3Catelog)) {
                                            // 封装成指定 vo 格式
                                            List<Catelog3Vo> catelog3VoList = level3Catelog.stream().map(l3 -> {
                                                Catelog3Vo catelog3Vo = Catelog3Vo.builder()
                                                        .catelog2Id(l2.getCatId().toString())
                                                        .id(l3.getCatId().toString())
                                                        .name(l3.getName())
                                                        .build();
                                                return catelog3Vo;
                                            }).collect(Collectors.toList());
                                            catelog2Vo.setCatalog3List(catelog3VoList);
                                        }
                                        return catelog2Vo;
                                    }).collect(Collectors.toList());
                                }
                                return catelog2VoList;
                            }
                    ));
            // 将查出的数据放入缓存, 并设置过期时间，防止缓存雪崩
            redisTemplate.opsForValue().set("catalogJSON", JSON.toJSONString(parentCid), 1, TimeUnit.DAYS);
            return parentCid;
        }

    }

    private List<CategoryEntity> getParentCid(List<CategoryEntity> selectList, Long parentCid) {
        List<CategoryEntity> categoryEntityList = selectList.stream()
                .filter(item -> item.getParentCid() == parentCid)
                .collect(Collectors.toList());
        return categoryEntityList;
    }

    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        // 收集当前节点id
        paths.add(catelogId);
        CategoryEntity categoryEntity = this.getById(catelogId);
        if (categoryEntity.getParentCid() != 0) {
            // 递归查询
            findParentPath(categoryEntity.getParentCid(), paths);
        }
        return paths;
    }

    /**
     * 递归查找所有菜单的子菜单
     * @param root
     * @param all
     * @return
     */
    private List<CategoryEntity> getChildrens(CategoryEntity root, List<CategoryEntity> all) {

        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid().equals(root.getCatId()))
                .map(categoryEntity -> {
                    // 找到子菜单
                    categoryEntity.setChildren(getChildrens(categoryEntity, all));
                    return categoryEntity;
                }).sorted((menu1, menu2) -> (Objects.isNull(menu1.getSort()) ? 0 : menu1.getSort()) - (Objects.isNull(menu2.getSort()) ? 0 : menu2.getSort()))
                .collect(Collectors.toList());
        return children;
    }

}